//
//  DownloadListVC.m
//  VideoPlayer
//
//  Created by 白璐 on 16/9/19.
//  Copyright © 2016年 baidu. All rights reserved.
//

#import "DownloadListVC.h"
#import "DownloadViewModel.h"
#import "VideoMediaCell.h"
#import "VideoDownloadingCell.h"
#import "PlayerViewModel.h"
#import "PlayerVC.h"

@interface DownloadListVC ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic, strong) DownloadViewModel* viewModel;
@end

@implementation DownloadListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof(self) wself = self;
    self.viewModel = [DownloadViewModel defaultModel];
    self.viewModel.updateBlock = ^(NSUInteger index) {
        __strong typeof(wself) sself = wself;
        [sself onUpdate:index];
    };
    
    NSUInteger count = [self.viewModel count];
    if (count == 0) {
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
}

- (void)dealloc {
    self.viewModel.updateBlock = nil;
}

- (void)onAction:(VideoDownloadingCell*)cell {
    CGPoint point = [self.tableView convertPoint:cell.center fromView:cell.superview];
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:point];
    [self.viewModel action:path.row cancelBlock:^(BOOL cancel) {
        if (!cancel) {
            [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
}

- (void)onStop:(VideoDownloadingCell*)cell {
    CGPoint point = [self.tableView convertPoint:cell.center fromView:cell.superview];
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:point];
    [self.viewModel stop:path.row];
    [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)onUpdate:(NSUInteger)index {
    NSIndexPath* path = [NSIndexPath indexPathForRow:index inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSUInteger count = [self.viewModel count];
    return count == 0 ? 1 : count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger count = [self.viewModel count];
    if (count == 0) {
        return [tableView dequeueReusableCellWithIdentifier:@"noVideoCell" forIndexPath:indexPath];
    }
    
    NSString* cellIdentifier = [self.viewModel cellIdentifier:indexPath.row];
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    if ([cellIdentifier isEqualToString:@"offlineCell"]) {
        VideoDownloadingCell* downloadingCell = (VideoDownloadingCell*)cell;
        __weak typeof(self) wself = self;
        downloadingCell.actionBlock = ^(VideoDownloadingCell* currentCell) {
            __strong typeof(wself) sself = wself;
            [sself onAction:currentCell];
        };
        
        downloadingCell.stopBlock =  ^(VideoDownloadingCell* currentCell) {
            __strong typeof(wself) sself = wself;
            [sself onStop:currentCell];
        };
    }
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView
        commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
        forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.viewModel remove:indexPath.row];
        NSUInteger count = [self.viewModel count];
        if (count != 0) {
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        } else {
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        }
    }
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger count = [self.viewModel count];
    return count != 0 ? 100 : 300;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)tableView:(UITableView *)tableView
            willDisplayCell:(UITableViewCell *)cell
            forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger count = [self.viewModel count];
    if (count == 0) {
        return;
    }
    
    NSUInteger row = indexPath.row;
    if ([cell isKindOfClass:[VideoMediaCell class]]) {
        VideoMediaCell *videoCell = (VideoMediaCell*)cell;
        videoCell.videoImageView.image = [UIImage imageNamed:[self.viewModel image:row]];
        videoCell.titleView.text = [self.viewModel title:row];
        videoCell.detailView.text = [self.viewModel detail:row];
        videoCell.downloadButton.hidden = YES;
        
    } else if ([cell isKindOfClass:[VideoDownloadingCell class]]) {
        VideoDownloadingCell* downloadCell = (VideoDownloadingCell*)cell;
        
        DownloadState state = [self.viewModel state:row];
        
        downloadCell.videoImageView.image = [UIImage imageNamed:[self.viewModel image:row]];
        downloadCell.titleView.text = [self.viewModel title:row];
        
        downloadCell.stopButton.hidden = (state == DownloadStateNone);
        downloadCell.stopButton.enabled = (state != DownloadStateNone);
        
        float progress = [self.viewModel progress:row];
        downloadCell.progressView.hidden = (state == DownloadStateNone || state == DownloadStateCompleted);
        downloadCell.progressView.progress = progress / 100;
        
        downloadCell.progressLabel.hidden = (state == DownloadStateNone || state == DownloadStateCompleted);
        downloadCell.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", progress];
        
        NSString* imageName = @"button_continue";
        if (state == DownloadStateRunning) {
            imageName = @"button_pause";
        }
        [downloadCell.actionButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
}

#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // get index
    UITableViewCell* cell = (UITableViewCell*)sender;
    CGPoint point = [self.tableView convertPoint:cell.center fromView:cell.superview];
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:point];
    NSUInteger row = path.row;
    
    // get url title
    NSString* url = [self.viewModel url:row];
    NSString* title = [self.viewModel title:row];
    NSString* token = [self.viewModel token:row];
    PlayerViewModel* viewModel = [[PlayerViewModel alloc] initWithURL:url
                                                                title:title
                                                         downloadable:NO
                                                                token:token];
    viewModel.videoSource = self.viewModel;
    
    PlayerVC* vc = (PlayerVC*)segue.destinationViewController;
    vc.viewModel = viewModel;
}

@end
